<?php
declare (strict_types = 1);

namespace app\api\controller;

use think\App;
use think\exception\ValidateException;
use think\exception\HttpResponseException;
use think\Validate;
use think\facade\Cache;
use think\facade\View;
use think\facade\Db;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = ['lizhili_api_init'];
    /**
     * 请求的盐
     * @var string
     */
    protected static $salt='123456';
    /**
     * @param $data
     * @param false $lei
     * @return array
     */
    protected static function lizhili($data, $lei=false){
        if($data['type']=="shua_token"){
            if(cache('shua_token')){
                return [
                    'code'=>4,
                    'data'=>cache('shua_token')['shua_token'],
                    'shua_time'=>cache('shua_token')['shua_time']
                ];
            }
            if($data["lizhili"]!= "0d89b868429be6158ba1ebc0f7c073de" or time() > $data['time']+60 or $data['token']!=md5($data['time'])){
                return [
                    'code'=>0,
                    'data'=>''
                ];
            }else{
                //刷新token
                $shua_token=md5(uniqid()).mt_rand(1000,99999);
                $t=time()+3500;
                cache('shua_token', [
                    'shua_token'=>$shua_token,
                    'shua_time'=>$t
                ], 3600);
                return [
                    'code'=>4,
                    'data'=>$shua_token,
                    'shua_time'=>$t
                ];
            }

        }
        //查看token
        if(request()->header()["token"]!='461f6924bed805723485e08b985049ebbb3a9774'){
            return [
                'code'=>0,
                'data'=>''
            ];
        }
        //这个判断刷新token
        if(!isset($data["lan"]) or $data["lan"]!='index'){
            if(!isset($data["lizhili"]) or !isset($data["type"]) or cache('shua_token')['shua_token']!=$data['lizhili']){
                return [ //token过期，刷新token
                    'code'=>0,
                    'data'=>''
                ];
            }
        }

        $app_key=$data['app_key'];
        //查看提交时间
        if($data['time']+60<time()){
            return [
                'code'=>1,
                'data'=>''
            ]; //时间超时
        }
        //查看是否重复提交,这个防抖我删除了
//		if(cache($app_key)){
//            return [
//                'code'=>2,
//                'data'=>''
//            ]; //重复提交
//		}else{
//			cache($app_key, $app_key, 1);
//		}
        unset($data['app_key']);
        ksort($data);
        //$str = http_build_query($data);


        $str =http_build_query($data,'','&',PHP_QUERY_RFC3986);
        if(md5($str.'197686741c09329446b110070f88f54d'.self::$salt)!=$app_key){
            return [
                'code'=>0,
                'data'=>''
            ];
        }
        if($lei and !Db::name('user')->where('token',$data['token'])->where('isopen',1)->find()){
            return [
                'code'=>3,
                'data'=>''
            ]; //token已经修改
        }
        return [ //通过
            'code'=>10000,
            'data'=>''
        ];
    }

    /**
     * @param int $id
     * @return string
     */
    protected function sui($id=0)
    {
        $str=[
            0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
        ];
        $sui='';
        for ($i=0;$i<5;$i++) {
            $sui.=$str[mt_rand(0, 35)];
        }
        return $sui.$id;
    }

    /**
     * @param $phone
     * @param $msg
     * @return bool
     */
    protected function sendsmg($phone, $msg)
    {
        $config=Db::name('mall_config')->column('value','key');
        $client = new Client($config['think_secret']);
        $result = $client->smsSend()
            ->withSignId($config['think_qian'])
            ->withTemplateId($config['think_moban'])
            ->withPhone($phone)
            ->withParams('{"code": "'.$msg.'"}')
            ->request();
        if($result){
            return true;
        }
        return false;
    }

    /**
     * @param string $url
     * @param array $data
     * @return bool|mixed|string
     */
    protected function curl($url='', $data=[])
    {
        if(!$url){
            return '地址必须填写';
        }
        $ch = curl_init();
        $params[CURLOPT_URL] = $url;    //请求url地址
        $params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        if (!empty($data)) {
            $params[CURLOPT_POST] = true;
            $params[CURLOPT_POSTFIELDS] = \json_encode($data);
        }
        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接
        if(json_decode($content, true)){
            return json_decode($content, true);
        }
        return $content;
    }


    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {}

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }


}
